package ru.btabank.dom.xpath.expression;

import java.util.ArrayList;
import java.util.Iterator;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class NodeSet implements NodeList {

    ArrayList nodes;

    public NodeSet() {
        nodes = new ArrayList(16);
    }

    public NodeSet(Node node) {
        this();
        this.add(node);
    }

    public int getLength() {
        return nodes.size();
    }

    public Node item(int index) {
        return (Node)nodes.get(index);
    }

    public void add(Node node) {
        if (!nodes.contains(node)) {
            nodes.add(node);
        }
    }

    public void add(NodeList nodeList) {
        for (int position = 0; position < nodeList.getLength(); position++) {
            this.add(nodeList.item(position));
        }
    }

    public void clear() {
        this.nodes.clear();
    }

    public String toString() {
        String buffer = "";
        Iterator iterator = nodes.iterator();
        while (iterator.hasNext()) {
            Node node = (Node)iterator.next();
            switch (node.getNodeType()) {
            case Node.ELEMENT_NODE:
                buffer = buffer.concat("Element: ").concat(node.getNodeName());
                break;
            case Node.ATTRIBUTE_NODE:
                buffer = buffer.concat("Attribute: ").concat(
                                                             node.getNodeName().concat("='")
                                                                 .concat(node.getNodeValue()).concat("'"));
                break;
            case Node.TEXT_NODE:
                buffer = buffer.concat("Text: '").concat(node.getNodeValue()).concat("'");
                break;
            case Node.COMMENT_NODE:
                buffer = buffer.concat("Comment: '").concat(node.getNodeValue()).concat("'");
                break;
            case Node.CDATA_SECTION_NODE:
                buffer = buffer.concat("CDATA: '").concat(node.getNodeValue()).concat("'");
                break;
            case Node.DOCUMENT_NODE:
                buffer = buffer.concat("Document");
                break;
            default:
                buffer = buffer.concat("Unknown node");
            }
            if (iterator.hasNext())
                buffer = buffer.concat("\n");
        }
        return buffer;
    }
}
